<?php
class BDA_Visualization {
    public static function init() {
        add_shortcode('bdadashboard', [__CLASS__, 'render_dashboard']);
        add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_assets']);
    }

    public static function enqueue_assets() {
        global $post;
        if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'bdadashboard')) {
            // 加载CSS
            wp_enqueue_style(
                'bda-dashboard',
                BDA_PLUGIN_URL . 'assets/css/dashboard.css',
                [],
                BDA_VERSION
            );

            // 加载Chart.js
            wp_enqueue_script(
                'chart-js',
                'https://cdn.jsdelivr.net/npm/chart.js',
                [],
                '3.7.1',
                true
            );

            // 加载自定义JS
            wp_enqueue_script(
                'bda-dashboard',
                BDA_PLUGIN_URL . 'assets/js/dashboard.js',
                ['jquery', 'chart-js'],
                BDA_VERSION,
                true
            );

            // 传递参数到前端
            wp_localize_script('bda-dashboard', 'bdaDashboard', [
                'api_url' => rest_url('bda/v1/analytics'),
                'segments_url' => rest_url('bda/v1/user-segments'),
                'export_url' => rest_url('bda/v1/export-report'),
                'nonce' => wp_create_nonce('wp_rest')
            ]);
        }
    }

    public static function render_dashboard($atts = []) {
        if (!current_user_can('manage_options')) {
            return '<div class="bda-error">需要管理员权限访问此仪表盘</div>';
        }

        ob_start(); ?>
        <div class="bda-dashboard">
            <div class="bda-header">
                <h2>数据分析仪表盘</h2>
                <div class="date-range-selector">
                    <input type="date" id="bda-start-date" value="<?php echo date('Y-m-01'); ?>">
                    <span>至</span>
                    <input type="date" id="bda-end-date" value="<?php echo date('Y-m-d'); ?>">
                    <button id="bda-update-charts" class="button button-primary">更新数据</button>
                    <button id="bda-export-report" class="button">导出报告</button>
                </div>
            </div>
            
            <div class="bda-grid">
                <div class="bda-card">
                    <h3>销售趋势</h3>
                    <canvas id="sales-chart" width="400" height="300"></canvas>
                </div>
                
                <div class="bda-card">
                    <h3>用户画像</h3>
                    <canvas id="user-segments-chart" width="400" height="300"></canvas>
                </div>
                
                <div class="bda-card">
                    <h3>用户分类统计</h3>
                    <div id="user-segments-details"></div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
}